package com.pet.controller.AI.sparkAI;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pet.entity.AI.AiContent;
import com.pet.entity.PetInfoQuestionnaire;
import com.pet.properties.AiSparkProperties;
import com.pet.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("AI")
@Slf4j
public class SparkAi {
    @Autowired
    private AiSparkProperties aiSparkProperties ;

    String petQuestionnaireEntityInfo = "{// 主要饮食（1、狗粮 2、自制食物）\n    private Integer dietStaple;\n\n    // 食欲情况（1、食欲不振 2、正常 3、食欲旺盛）\n    private Integer dietAppetite;\n\n    // 进食情况（1、正常 2、不正常）\n    private Integer dietEat;\n\n    // 挑食情况（1、挑食 2、不挑食）\n    private Integer dietPicky;\n\n    // 拒食情况（1、拒食 2、不拒食）\n    private Integer dietApastia;\n\n    // 饮水情况（1、少饮 2、正常 3、多饮）\n    private Integer dietWater;\n\n    // 日常精神状态（1、不活泼 2、活泼）\n    private Integer dailySpirit;\n\n    // 是否异常叫唤（1、是 2、不是）\n    private Integer dailyAbnormalCall;\n\n    // 是否异常行为（1、是 2、不是）\n    private Integer dailyAbnormalAction;\n\n    // 是否有正常的回应（1、是 2、不是）\n    private Integer socialRespond;\n\n    // 行为表现（1、攻击性 2、正常 3、胆怯）\n    private Integer socialAction;\n\n    // 排泄物是否正常（1、正常 2、不正常）\n    private Integer excretionNormal;\n\n    // 排泄是否异常（1、正常 2、腹泻 3、便秘 4、便血）\n    private Integer excretionIllness;\n\n    // 尿液是否正常（1、正常 2、不正常）\n    private Integer excretionUrine;\n\n    // 排尿是否正常（1、正常 2、尿频 3、尿急 4、困难 5、尿血）\n    private Integer excretionUrineIllness;\n\n    // 是否有异味（1、正常 2、不正常）\n    // 注意：变量名中的下划线被移除了，因为Java变量名不允许包含下划线作为前缀或单词间的分隔\n    private Integer signSmell;\n\n    // 毛发是否光泽（1、正常 2、不正常）\n    private Integer signHair;\n\n    // 毛发是否异常（1、正常 2、脱毛 3、皮屑 4、红肿 5、伤口）\n    private Integer signHairIllness;\n\n    // 体重情况（1、减少 2、正常 3、增加）\n    private Integer signHeight;\n\n    // 呼吸情况（1、正常 2、咳嗽 3、打喷嚏）\n    private Integer signIllness01;\n\n    // 是否鼻涕或流口水(1、正常 2、流鼻涕 3、流口水)\n    private Integer signIllness02;\n\n    //宠物外键\n    private Integer petId;\n\n    //是否接种疫苗(1、接种疫苗 0、未接种疫苗)\n    private Integer vaccine;\n\n    //接种疫苗时间（(0、3个月内；1、3-12月内；2、1-3年内；3、3年以上)）\n    private Integer vaccineDate;\n\n    //补充内容\n    private String extraInfo;\n}\n";

    //创建一个函数 aiTalkWithEntity(),该函数可以接收任意类型的参数，返回一个String对象

    @PostMapping("sparkTalk")
    public Result sparkTalk(@RequestBody AiContent aiContent) throws IOException {

        // 创建HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            log.info("AiContent:{}",aiContent);
            log.info("AiSparkProperties:{}",aiSparkProperties);
            // 创建HttpPost请求
            HttpPost httpPost = new HttpPost(aiSparkProperties.getHttpPost());

            // 设置请求头
            httpPost.setHeader("Authorization", aiSparkProperties.getAuthorization());
            httpPost.setHeader("Content-Type", "application/json");

            // 创建JSON请求体
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("model", aiSparkProperties.getModel());
            JSONObject message = new JSONObject();
            message.put("role", "user");
            message.put("content", "现在请你扮演宠物健康、信息管理员，只回答与宠物相关的问题，如果遇到非宠物相关问题请回答“拒绝回答”以下是我的问题：" + aiContent.getContent()+"，不超过500字");
            log.info("问答：{}",message.getString("content"));
            jsonObject.put("messages", java.util.Collections.singletonList(message));
            //jsonObject.put("stream", true);

            // 将JSON对象转换为字符串，并设置为请求体
            StringEntity entity = new StringEntity(jsonObject.toJSONString(), "UTF-8");
            httpPost.setEntity(entity);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("Response Code: " + statusCode);

                // 获取响应体
                HttpEntity responseEntity = response.getEntity();
                String responseBody = EntityUtils.toString(responseEntity, "UTF-8");
                //打印返回的详细数据
                System.out.println("Response Body: " + responseBody);
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode rootNode = objectMapper.readTree(responseBody);
                    // 导航到choices数组，并获取第一个元素的message对象的content字段
                    JsonNode choicesNode = rootNode.get("choices");
                    if (choicesNode != null && choicesNode.isArray() && choicesNode.size() > 0) {
                        JsonNode firstChoiceNode = choicesNode.get(0);
                        JsonNode messageNode = firstChoiceNode.get("message");
                        if (messageNode != null) {
                            JsonNode contentNode = messageNode.get("content");
                            if (contentNode != null) {
                                String content = contentNode.asText();
                                System.out.println("Content: " + content);
                                return Result.success(content);
                            }
                        }
                    }

                    // 如果未找到content，可以返回一个错误或默认值
                    return Result.error("Content not found in response");
                } catch (Exception e) {
                    e.printStackTrace();
                    return Result.error("Error parsing JSON response");
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success();
    }

    @PostMapping("/sparkTalkStream")
    private Result sparkTalkStream(@RequestBody AiContent aiContent) throws IOException {
        // 创建HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 打印请求的AiContent对象信息
            log.info("AiContent: {}", aiContent);
            // 打印配置的AiSparkProperties信息
            log.info("AiSparkProperties: {}", aiSparkProperties);

            // 创建HttpPost请求
            HttpPost httpPost = new HttpPost(aiSparkProperties.getHttpPost());
            log.info("HttpPost URL: {}", aiSparkProperties.getHttpPost());

            // 设置请求头
            httpPost.setHeader("Authorization", aiSparkProperties.getAuthorization());
            httpPost.setHeader("Content-Type", "application/json");
            log.info("Request Header Authorization: {}", aiSparkProperties.getAuthorization());
            log.info("Request Header Content-Type: {}", "application/json");

            // 创建JSON请求体
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("model", aiSparkProperties.getModel());
            JSONObject message = new JSONObject();
            message.put("role", "user");
            message.put("content", aiContent.getContent() + "不超过100字");
            jsonObject.put("messages", java.util.Collections.singletonList(message));
            jsonObject.put("stream", true);

            // 将JSON对象转换为字符串，并设置为请求体
            StringEntity entity = new StringEntity(jsonObject.toJSONString(), "UTF-8");
            httpPost.setEntity(entity);
            log.info("Request JSON Body: {}", jsonObject.toJSONString());

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                log.info("Response Status Code: {}", statusCode);

                // 获取响应体
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String responseBody = EntityUtils.toString(responseEntity, "UTF-8");
                    log.info("Response Body: {}", responseBody);
                    return Result.success(responseBody);
                } else {
                    log.warn("Response Entity is null");
                }
            } catch (IOException e) {
                log.error("Error occurred during HTTP request", e);
            }
        }
        return Result.success();
    }

    @PostMapping("/ai")
    public Result petInfoQuestionnaireAi(PetInfoQuestionnaire petInfoQuestionnaire) throws IOException {
        // 创建HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            log.info("AiContent:{}",petInfoQuestionnaire);
            log.info("AiSparkProperties:{}",aiSparkProperties);
            // 创建HttpPost请求
            HttpPost httpPost = new HttpPost(aiSparkProperties.getHttpPost());

            // 设置请求头
            httpPost.setHeader("Authorization", aiSparkProperties.getAuthorization());
            httpPost.setHeader("Content-Type", "application/json");

            // 创建JSON请求体
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("model", aiSparkProperties.getModel());
            JSONObject message = new JSONObject();
            message.put("role", "user");
            message.put("content", "现在请你扮演宠物健康、信息管理员，只回答与宠物相关的问题，如果遇到非宠物相关问题请回答“拒绝回答”" +
                    "请根据：\n" +
                    "1:" + petQuestionnaireEntityInfo + "类中的注释信息\n" +
                    "2:用户实际问卷内容：" + petInfoQuestionnaire +"\n"+
                    "分点给出养宠建议，不超过500字");
            jsonObject.put("messages", java.util.Collections.singletonList(message));
            //jsonObject.put("stream", true);

            // 将JSON对象转换为字符串，并设置为请求体
            StringEntity entity = new StringEntity(jsonObject.toJSONString(), "UTF-8");
            httpPost.setEntity(entity);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("Response Code: " + statusCode);

                // 获取响应体
                HttpEntity responseEntity = response.getEntity();
                String responseBody = EntityUtils.toString(responseEntity, "UTF-8");
                //打印返回的详细数据
                System.out.println("Response Body: " + responseBody);
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode rootNode = objectMapper.readTree(responseBody);
                    // 导航到choices数组，并获取第一个元素的message对象的content字段
                    JsonNode choicesNode = rootNode.get("choices");
                    if (choicesNode != null && choicesNode.isArray() && choicesNode.size() > 0) {
                        JsonNode firstChoiceNode = choicesNode.get(0);
                        JsonNode messageNode = firstChoiceNode.get("message");
                        if (messageNode != null) {
                            JsonNode contentNode = messageNode.get("content");
                            if (contentNode != null) {
                                String content = contentNode.asText();
                                System.out.println("Content: " + content);
                                return Result.success(content);
                            }
                        }
                    }

                    // 如果未找到content，可以返回一个错误或默认值
                    return Result.error("Content not found in response");
                } catch (Exception e) {
                    e.printStackTrace();
                    return Result.error("Error parsing JSON response");
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success();
    }
}
